<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">

		<title>Document</title>
		<style>
			* {
				margin: 0px;

			}
		</style>


	</head>
	<body>
		<video id="video" width="800" height="500"></video>
		<canvas id="canvas" width="800" height="500"></canvas>
		<a id="down" style="opacity: 0;"></a>

		<!-- <div>
			<button id="snap">拍照</button>
		</div> -->

		<!-- https://blog.csdn.net/qq_36727889/article/details/91402854 -->

		<script>
			//用来匹配不同的浏览器
			function getUserMedia(constraints, success, error) {
				if (navigator.mediaDevices.getUserMedia) {
					navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
				} else if (navigator.webkitGetUserMedia) {
					navigator.webkitGetUserMedia(constraints, success, error);
				} else if (navigator.mozGetUserMedia) {
					navigator.mozGetUserMedia(constraints, success, error);
				} else if (navigator.getUserMedia) {
					navigator.getUserMedia(constraints, success, error)
				}
			}

			let video = document.getElementById('video');
			let canvas = document.getElementById('canvas');
			let context = canvas.getContext('2d');
			//成功回调
			function success(stream) {
				video.srcObject = stream;
				video.play();
			}
			//失败回调
			function error(error) {
				console.log("访问用户媒体失败");
			}
			//开启摄像头
			if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator
				.mozGetUserMedia) {
				getUserMedia({
					video: {
						width: 800,
						height: 500
					}
				}, success, error)
			} else {
				alert("不支持");
			}
			//实现拍照的功能
			// document.getElementById('snap').addEventListener('click', function() {
			// 	context.drawImage(video, 0, 0, 800, 500);
			// });

			// ctx = c.getContext('2d');

			//每 1000 毫秒，代码就会绘制视频的当前帧，数值修改

			video.addEventListener('play', function() {
				var i = window.setInterval(function() {
					context.drawImage(video, 0, 0, 800, 500);
					getImg();
				}, 1000);
			}, false);
			video.addEventListener('pause', function() {
				window.clearInterval(i);
				
			}, false);
			
			video.addEventListener('ended', function() {
				clearInterval(i);
			}, false);

			//如果需要将拍下来的图片传送给服务器，那么还需要将图片转成base64码
			// imgData = canvas.toDataURL();
			// var photo = imgData.substr(22);


			// OpenCV摄像头获取视频并实时保存每帧图片
			// https://blog.csdn.net/qq_28713863/article/details/77995663
			
			// 保存图片到本地
			function getImg(){
				
				// 定义一个img
				var img = new Image();
				//设置属性和src
				img.id = "newImg";
				img.src = image;
				img.onload = function(){
					let a = document.getElementById('down');
					a.appendChild(img)
					a.href=image;
					a.download='aaa'; // 下载的图片的名称
					a.click()
				}
				
			}

		</script>

	</body>
</html>
